import { useState, useEffect } from 'react'
import { STATUS_CONFIG, getStatusColor, getStatusName, getNextStatus, StatusKey } from './config/statusConfig'
// import './types/electron'
import './App.css'

interface Phone {
  number: string
  status: StatusKey
  isLocal: boolean
  lastStatusChanged?: string
}

interface Company {
  id: number
  companyName: string
  phones: (Phone | null)[]
  status: 'completed' | 'pending'
  notes: string
}

type SortField = 'id' | 'companyName' | 'status' | 'phone1' | 'phone2' | 'phone3'
type SortDirection = 'asc' | 'desc'

function App() {
  const [companies, setCompanies] = useState<Company[]>([])
  const [contextMenu, setContextMenu] = useState<{
    visible: boolean
    x: number
    y: number
    companyId: number
    phoneIndex: number
  }>({
    visible: false,
    x: 0,
    y: 0,
    companyId: 0,
    phoneIndex: 0
  })
  const [tooltip, setTooltip] = useState<{
    visible: boolean
    x: number
    y: number
    content: string
  }>({
    visible: false,
    x: 0,
    y: 0,
    content: ''
  })
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1)
  const [itemsPerPage, setItemsPerPage] = useState(5)
  // 排序状态
  const [sortField, setSortField] = useState<SortField>('id')
  const [sortDirection, setSortDirection] = useState<SortDirection>('asc')
  // 编辑备注状态
  const [editingNotes, setEditingNotes] = useState<{
    companyId: number | null
    value: string
  }>({
    companyId: null,
    value: ''
  })

  // 格式化时间显示
  const formatLastChanged = (timestamp?: string): string => {
    if (!timestamp) return '暂无记录'
    
    const date = new Date(timestamp)
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
    const diffDays = Math.floor(diffHours / 24)
    
    if (diffDays > 0) {
      return `${diffDays}天前 (${date.toLocaleDateString()} ${date.toLocaleTimeString()})`
    } else if (diffHours > 0) {
      return `${diffHours}小时前 (${date.toLocaleTimeString()})`
    } else {
      const diffMinutes = Math.floor(diffMs / (1000 * 60))
      if (diffMinutes > 0) {
        return `${diffMinutes}分钟前 (${date.toLocaleTimeString()})`
      } else {
        return `刚刚 (${date.toLocaleTimeString()})`
      }
    }
  }

  // 悬浮事件处理
  const handleMouseEnter = (event: React.MouseEvent, phone: Phone | null) => {
    if (!phone) return
    const rect = event.currentTarget.getBoundingClientRect()
    setTooltip({
      visible: true,
      x: rect.left + rect.width / 2,
      y: rect.top - 10,
      content: `状态: ${getStatusName(phone.status)}\n${phone.isLocal ? '本地号码\n' : ''}最后变更: ${formatLastChanged(phone.lastStatusChanged)}`
    })
  }

  const handleMouseLeave = () => {
    setTooltip({ ...tooltip, visible: false })
  }

  // 排序处理函数
  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortDirection('asc')
    }
    setCurrentPage(1)
  }

  // 获取电话状态用于排序
  const getPhoneStatusForSort = (phone: Phone | null): string => {
    if (!phone) return 'zzz' // 空电话排在最后
    return phone.status
  }

  // 排序数据
  const sortedCompanies = [...companies].sort((a, b) => {
    let aValue: string | number
    let bValue: string | number

    switch (sortField) {
      case 'id':
        aValue = a.id
        bValue = b.id
        break
      case 'companyName':
        aValue = a.companyName
        bValue = b.companyName
        break
      case 'status':
        aValue = a.status
        bValue = b.status
        break
      case 'phone1':
        aValue = getPhoneStatusForSort(a.phones[0])
        bValue = getPhoneStatusForSort(b.phones[0])
        break
      case 'phone2':
        aValue = getPhoneStatusForSort(a.phones[1])
        bValue = getPhoneStatusForSort(b.phones[1])
        break
      case 'phone3':
        aValue = getPhoneStatusForSort(a.phones[2])
        bValue = getPhoneStatusForSort(b.phones[2])
        break
      default:
        aValue = a.id
        bValue = b.id
    }

    if (aValue < bValue) return sortDirection === 'asc' ? -1 : 1
    if (aValue > bValue) return sortDirection === 'asc' ? 1 : -1
    return 0
  })

  // 分页数据
  const totalItems = sortedCompanies.length
  const totalPages = Math.ceil(totalItems / itemsPerPage)
  const startIndex = (currentPage - 1) * itemsPerPage
  const endIndex = startIndex + itemsPerPage
  const currentPageData = sortedCompanies.slice(startIndex, endIndex)

  // 分页导航函数
  const goToPage = (page: number) => {
    setCurrentPage(Math.max(1, Math.min(page, totalPages)))
  }

  useEffect(() => {
    fetch('/data.json')
      .then(response => response.json())
      .then(data => setCompanies(data))
      .catch(error => console.error('Error loading data:', error))
  }, [])

  // 保存数据到JSON文件
  const saveData = async (newData: Company[]) => {
    try {
      if (window.electron) {
        await window.electron.ipcRenderer.invoke('save-data', newData)
      } else {
        localStorage.setItem('phoneData', JSON.stringify(newData))
        console.log('Data saved to localStorage')
      }
    } catch (error) {
      console.error('Error saving data:', error)
    }
  }

  // 左键点击电话切换状态
  const handlePhoneClick = (companyId: number, phoneIndex: number) => {
    const currentTime = new Date().toISOString()
    const newCompanies = companies.map(company =>
      company.id === companyId
        ? {
            ...company,
            phones: company.phones.map((phone, index) =>
              index === phoneIndex && phone
                ? { 
                    ...phone, 
                    status: getNextStatus(phone.status) as StatusKey,
                    lastStatusChanged: currentTime
                  }
                : phone
            )
          }
        : company
    )
    setCompanies(newCompanies)
    saveData(newCompanies)
  }

  // 左键点击公司名切换状态
  const handleCompanyStatusClick = (companyId: number) => {
    const newCompanies = companies.map(company =>
      company.id === companyId
        ? {
            ...company,
            status: company.status === 'completed' ? 'pending' : 'completed' as 'completed' | 'pending'
          }
        : company
    )
    setCompanies(newCompanies)
    saveData(newCompanies)
  }

  // 右键点击公司名编辑备注
  const handleCompanyNotesContextMenu = (event: React.MouseEvent, companyId: number) => {
    event.preventDefault()
    const company = companies.find(c => c.id === companyId)
    if (company) {
      setEditingNotes({
        companyId: companyId,
        value: company.notes
      })
    }
  }

  // 保存备注
  const saveNotes = () => {
    if (editingNotes.companyId) {
      const newCompanies = companies.map(company =>
        company.id === editingNotes.companyId
          ? { ...company, notes: editingNotes.value }
          : company
      )
      setCompanies(newCompanies)
      saveData(newCompanies)
    }
    setEditingNotes({ companyId: null, value: '' })
  }

  const handleContextMenu = (event: React.MouseEvent, companyId: number, phoneIndex: number) => {
    event.preventDefault()
    const phone = companies.find(c => c.id === companyId)?.phones[phoneIndex]
    if (phone) {
      setContextMenu({
        visible: true,
        x: event.clientX,
        y: event.clientY,
        companyId,
        phoneIndex
      })
    }
  }

  const handleStatusChange = (status: StatusKey) => {
    const currentTime = new Date().toISOString()
    const newCompanies = companies.map(company =>
      company.id === contextMenu.companyId
        ? {
            ...company,
            phones: company.phones.map((phone, index) =>
              index === contextMenu.phoneIndex && phone
                ? { ...phone, status, lastStatusChanged: currentTime }
                : phone
            )
          }
        : company
    )
    setCompanies(newCompanies)
    saveData(newCompanies)
    setContextMenu({ ...contextMenu, visible: false })
  }

  const handleLocalToggle = () => {
    const newCompanies = companies.map(company =>
      company.id === contextMenu.companyId
        ? {
            ...company,
            phones: company.phones.map((phone, index) =>
              index === contextMenu.phoneIndex && phone
                ? { ...phone, isLocal: !phone.isLocal }
                : phone
            )
          }
        : company
    )
    setCompanies(newCompanies)
    saveData(newCompanies)
    setContextMenu({ ...contextMenu, visible: false })
  }

  const handleClickOutside = () => {
    setContextMenu({ ...contextMenu, visible: false })
    setEditingNotes({ companyId: null, value: '' })
  }

  return (
    <div className='App' onClick={handleClickOutside}>
      <h1>公司电话号码管理系统</h1>
      <div className='instructions'>
        <p>🖱️ 左键点击电话号码：循环切换状态</p>
        <p>🖱️ 左键点击公司名：切换完成/未完成状态</p>
        <p>🖱️ 右键点击电话号码：打开菜单选择状态或标注本地号码</p>
        <p>🖱️ 右键点击公司名：编辑备注</p>
        <p>🖱️ 悬浮在电话号码上：查看状态变更时间</p>
        <p>📊 点击表头：按该字段排序</p>
        <p>📄 使用底部分页导航：浏览不同页面的数据</p>
      </div>
      <div className='table-container'>
        <div className='table-info'>
          <span>共 {totalItems} 条记录，第 {currentPage}/{totalPages} 页</span>
          <div className='items-per-page'>
            <label>每页显示：</label>
            <select 
              value={itemsPerPage} 
              onChange={(e) => {
                setItemsPerPage(Number(e.target.value))
                setCurrentPage(1)
              }}
            >
              <option value={5}>5条</option>
              <option value={10}>10条</option>
              <option value={20}>20条</option>
              <option value={50}>50条</option>
            </select>
          </div>
        </div>
        
        <table className='data-table'>
          <thead>
            <tr>
              <th 
                className={`sortable ${sortField === 'id' ? 'sorted' : ''}`}
                onClick={() => handleSort('id')}
              >
                序号
                {sortField === 'id' && (
                  <span className='sort-indicator'>
                    {sortDirection === 'asc' ? ' ↑' : ' ↓'}
                  </span>
                )}
              </th>
              <th 
                className={`sortable ${sortField === 'companyName' ? 'sorted' : ''}`}
                onClick={() => handleSort('companyName')}
              >
                公司名字
                {sortField === 'companyName' && (
                  <span className='sort-indicator'>
                    {sortDirection === 'asc' ? ' ↑' : ' ↓'}
                  </span>
                )}
              </th>
              <th 
                className={`sortable ${sortField === 'status' ? 'sorted' : ''}`}
                onClick={() => handleSort('status')}
              >
                状态
                {sortField === 'status' && (
                  <span className='sort-indicator'>
                    {sortDirection === 'asc' ? ' ↑' : ' ↓'}
                  </span>
                )}
              </th>
              <th 
                className={`sortable ${sortField === 'phone1' ? 'sorted' : ''}`}
                onClick={() => handleSort('phone1')}
              >
                电话号码1
                {sortField === 'phone1' && (
                  <span className='sort-indicator'>
                    {sortDirection === 'asc' ? ' ↑' : ' ↓'}
                  </span>
                )}
              </th>
              <th 
                className={`sortable ${sortField === 'phone2' ? 'sorted' : ''}`}
                onClick={() => handleSort('phone2')}
              >
                电话号码2
                {sortField === 'phone2' && (
                  <span className='sort-indicator'>
                    {sortDirection === 'asc' ? ' ↑' : ' ↓'}
                  </span>
                )}
              </th>
              <th 
                className={`sortable ${sortField === 'phone3' ? 'sorted' : ''}`}
                onClick={() => handleSort('phone3')}
              >
                电话号码3
                {sortField === 'phone3' && (
                  <span className='sort-indicator'>
                    {sortDirection === 'asc' ? ' ↑' : ' ↓'}
                  </span>
                )}
              </th>
            </tr>
          </thead>
          <tbody>
            {currentPageData.map((company, index) => (
              <tr key={company.id}>
                <td>{startIndex + index + 1}</td>
                <td>
                  <div className='company-cell'>
                    <div
                      className={`company-name ${company.status === 'completed' ? 'completed' : 'pending'}`}
                      onClick={() => handleCompanyStatusClick(company.id)}
                      onContextMenu={(e) => handleCompanyNotesContextMenu(e, company.id)}
                      title={`点击切换状态 | 当前: ${company.status === 'completed' ? '已完成' : '未完成'}`}
                    >
                      {company.companyName}
                      <span className={`status-badge ${company.status}`}>
                        {company.status === 'completed' ? '✓' : '○'}
                      </span>
                    </div>
                    {company.notes && (
                      <div className='company-notes' title={company.notes}>
                        📝 {company.notes}
                      </div>
                    )}
                  </div>
                </td>
                <td>
                  <span className={`company-status ${company.status}`}>
                    {company.status === 'completed' ? '已完成' : '未完成'}
                  </span>
                </td>
                {company.phones.map((phone, phoneIndex) => (
                  <td key={phoneIndex}>
                    {phone ? (
                      <span
                        className={`phone-number ${phone.isLocal ? 'local-phone' : ''}`}
                        style={{ color: getStatusColor(phone.status) }}
                        onClick={() => handlePhoneClick(company.id, phoneIndex)}
                        onContextMenu={(e) => handleContextMenu(e, company.id, phoneIndex)}
                        onMouseEnter={(e) => handleMouseEnter(e, phone)}
                        onMouseLeave={handleMouseLeave}
                        title={`状态: ${getStatusName(phone.status)}${phone.isLocal ? ' | 本地号码' : ''}`}
                      >
                        {phone.number}
                        {phone.isLocal && <span className='local-indicator'>📍</span>}
                      </span>
                    ) : (
                      <span className='empty-phone'>-</span>
                    )}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>

        {/* 分页导航 */}
        <div className='pagination'>
          <button 
            className='pagination-btn'
            onClick={() => goToPage(1)}
            disabled={currentPage === 1}
          >
            首页
          </button>
          <button 
            className='pagination-btn'
            onClick={() => goToPage(currentPage - 1)}
            disabled={currentPage === 1}
          >
            上一页
          </button>
          
          <div className='pagination-pages'>
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNum
              if (totalPages <= 5) {
                pageNum = i + 1
              } else if (currentPage <= 3) {
                pageNum = i + 1
              } else if (currentPage >= totalPages - 2) {
                pageNum = totalPages - 4 + i
              } else {
                pageNum = currentPage - 2 + i
              }
              
              return (
                <button
                  key={pageNum}
                  className={`pagination-btn ${currentPage === pageNum ? 'active' : ''}`}
                  onClick={() => goToPage(pageNum)}
                >
                  {pageNum}
                </button>
              )
            })}
          </div>

          <button 
            className='pagination-btn'
            onClick={() => goToPage(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            下一页
          </button>
          <button 
            className='pagination-btn'
            onClick={() => goToPage(totalPages)}
            disabled={currentPage === totalPages}
          >
            尾页
          </button>
        </div>
      </div>

      {/* 右键菜单 */}
      {contextMenu.visible && (
        <div
          className='context-menu'
          style={{
            position: 'fixed',
            left: contextMenu.x,
            top: contextMenu.y,
            zIndex: 1000
          }}
          onClick={(e) => e.stopPropagation()}
        >
          <div className='menu-section'>
            <div className='menu-section-title'>状态设置</div>
            {STATUS_CONFIG.map((config) => (
              <div
                key={config.key}
                className='menu-item'
                onClick={() => handleStatusChange(config.key as StatusKey)}
              >
                <span className='status-color' style={{ backgroundColor: config.color }}></span>
                {config.name}
              </div>
            ))}
          </div>
          <div className='menu-divider'></div>
          <div className='menu-section'>
            <div className='menu-section-title'>本地号码设置</div>
            <div className='menu-item' onClick={handleLocalToggle}>
              <span className='local-icon'>📍</span>
              {(() => {
                const currentPhone = companies
                  .find(c => c.id === contextMenu.companyId)
                  ?.phones[contextMenu.phoneIndex]
                return currentPhone?.isLocal ? '取消本地号码标注' : '标注为本地号码'
              })()}
            </div>
          </div>
        </div>
      )}

      {/* 悬浮提示 */}
      {tooltip.visible && (
        <div
          className='tooltip'
          style={{
            left: tooltip.x,
            top: tooltip.y,
          }}
        >
          {tooltip.content}
        </div>
      )}

      {/* 编辑备注弹窗 */}
      {editingNotes.companyId && (
        <div className='modal-overlay' onClick={handleClickOutside}>
          <div className='modal' onClick={(e) => e.stopPropagation()}>
            <h3>编辑备注</h3>
            <textarea
              value={editingNotes.value}
              onChange={(e) => setEditingNotes({ ...editingNotes, value: e.target.value })}
              placeholder='请输入备注信息...'
              rows={4}
              autoFocus
            />
            <div className='modal-actions'>
              <button onClick={saveNotes}>保存</button>
              <button onClick={() => setEditingNotes({ companyId: null, value: '' })}>取消</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default App